﻿using Autofac;
using Autofac.Core;
using Castle.Core.Interceptor;
using Orchard.Data.Migration;
using Orchard.Environment.AutofacUtil.DynamicProxy2;
using Module = Autofac.Module;

namespace Szmyd.Infiltrator.Autofac
{
    public class ProxyModule : Module
    {
        protected override void Load(ContainerBuilder moduleBuilder) {
            moduleBuilder.RegisterType<CallInterceptor>().InstancePerDependency();
        }

        protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) {
            var context = DynamicProxyContext.From(registration);
            if(context != null) {
                // Need to filter out IDataMigration implementations - those are heavily reflected on
                if (registration.Activator.LimitType.Namespace != null 
                    && !typeof(IDataMigration).IsAssignableFrom(registration.Activator.LimitType)
                    && !typeof(IProfilingManager).IsAssignableFrom(registration.Activator.LimitType)
                    && !typeof(IInterceptor).IsAssignableFrom(registration.Activator.LimitType)
                    && !typeof(Module).IsAssignableFrom(registration.Activator.LimitType)
                    && !registration.Activator.LimitType.Namespace.StartsWith("Orchard.Data"))
                {
                    registration.InterceptedBy<CallInterceptor>();
                }
            }
        }
    }
}